import { BeforeInsert, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
import * as bcrypt from "bcryptjs";
import { Exclude } from "class-transformer";
import { ApiProperty } from "@nestjs/swagger";
export enum UserRole {
	root = "root",
	admin = "admin",
	author = "author",
	visitor = "visitor"
}
@Entity("users")
export class Users {
	@ApiProperty({ description: "用户id" })
	@PrimaryGeneratedColumn("uuid")
	id: string;

	@ApiProperty({ description: "用户名" })
	@Column({ unique: true, comment: "用户名", length: 100, default: null })
	account: string;

	@ApiProperty({ description: "昵称" })
	@Column({ comment: "昵称", length: 100 })
	nickname: string;

	@ApiProperty({ description: "密码" })
	@Exclude()
	@Column({ comment: "密码", select: false })
	password: string;

	@ApiProperty({ description: "头像" })
	@Column({ comment: "头像", default: null })
	avatar: string;

	@ApiProperty({ description: "邮件" })
	@Column({ comment: "邮件", default: null })
	email: string;

	@ApiProperty({ description: "开放ID" })
	@Column({ comment: "开放ID", default: null })
	openid: string;

	@ApiProperty({ description: "用户身份" })
	@Column("enum", {
		comment: "用户身份",
		enum: ["root", "admin", "author", "visitor"],
		default: "visitor"
	})
	role: string;

	@ApiProperty({ description: "创建时间" })
	@Column({
		comment: "创建时间",
		type: "timestamp",
		default: () => "CURRENT_TIMESTAMP"
	})
	createTime: Date;

	@ApiProperty({ description: "修改时间" })
	@Exclude()
	@Column({
		type: "timestamp",
		comment: "修改时间",
		default: () => "CURRENT_TIMESTAMP"
	})
	updateTime: Date;

	@BeforeInsert()
	async encryptPwd() {
		if (!this.password) return;
		this.password = await bcrypt.hashSync(this.password, 10);
	}
}
